import Taro from '@tarojs/taro'

import { getToken, removeToken } from 'src/utils/app'

let baseurl = 'https://www.tocj1314.com/api/front/'
if (process.env.NODE_ENV === 'development') {
  baseurl = 'https://www.tocj1314.com/api/front/'
}

/**
 * 发送请求
 */
function request(url: string, options: any = {}): Promise<any> {
  const { method = 'GET', data, header = {} } = options

  const token = getToken()
  if (token) {
    header['Authori-zation'] = token
  }

  return new Promise((reslove, reject) => {
    Taro.request({
      url: baseurl + url,
      method,
      header,
      data,
      success: (res) => {
        if (res.data.code == 200) {
          reslove(res.data.data)
        } else if (
          [410000, 410001, 410002, 401].indexOf(res.data.code) !== -1
        ) {
          removeToken()
          Taro.switchTab({
            url: '/pages/user/index',
          })
        } else reject(res.data.message || '系统错误')
      },
      fail: () => {
        reject('请求失败')
      },
    })
  })
}

export default request
